package com.gzxx.security;

import com.google.common.collect.Lists;
import com.gzxx.domain.vo.SysRoleVo;
import com.gzxx.service.SysMenuService;
import com.gzxx.service.SysRoleService;
import com.gzxx.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;

/**
 * @author MAX
 * @date 2020/7/23 6:25 下午
 * 自定义用户认证服务
 */

@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserDetailsServiceImpl implements UserDetailsService {

    private final SysUserService sysUserService;
    private final SysRoleService sysRoleService;
    private final SysMenuService sysMenuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        CurrentUser currentUser = sysUserService.loadByUserName(username);
        if (currentUser == null) {
            throw new UsernameNotFoundException(String.format("User with %s was not found", username));
        }

        //获取系统用户角色
        SysRoleVo role = sysRoleService.getByUserId(currentUser.getId());
        Assert.notNull(role, "系统用户未分配角色或角色未授权");

        //填充权限
        Collection<SimpleGrantedAuthority> authorities = new HashSet<SimpleGrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
        currentUser.setRoleId(role.getId().intValue());

        //填充菜单权限
        List<Long> ids = Lists.newArrayList();
        ids.add(role.getId());
        List<String> menuPerms = sysMenuService.getMenuPermsByRoleIds(ids);

        currentUser.setAuthorities(authorities);
        currentUser.setPermissions(menuPerms);
        return currentUser;
    }
}
